import { defineStore } from 'pinia'
import { authAPI } from '@/api/auth'
import { organizationAPI } from '@/api/organization'

interface User {
  id: number
  name: string
  avatar: string
  isAdmin: boolean
  role?: string
}

interface Organization {
  id: number
  name: string
  code: string
  status: string
}

interface AppState {
  sidebar: {
    opened: boolean
    withoutAnimation: boolean
  }
  device: string
  currentOrganization: Organization | null
  userOrganizations: Organization[]
  unreadCount: number
  showUnreadCount: boolean
  user: User | null
  token: string | null
  roles: string[]
  pageTitle: string
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    sidebar: {
      opened: true,
      withoutAnimation: false
    },
    device: 'desktop',
    currentOrganization: null,
    userOrganizations: [],
    unreadCount: 0,
    showUnreadCount: false,
    user: null,
    token: localStorage.getItem('token'), // 从localStorage获取token
    roles: [],
    pageTitle: ''
  }),
  
  actions: {
    toggleSideBar() {
      this.sidebar.opened = !this.sidebar.opened
      this.sidebar.withoutAnimation = false
    },
    
    closeSideBar(withoutAnimation: boolean) {
      this.sidebar.opened = false
      this.sidebar.withoutAnimation = withoutAnimation
    },
    
    toggleDevice(device: string) {
      this.device = device
    },
    
    setCurrentOrganization(organization: Organization) {
      this.currentOrganization = organization
    },
    
    setUserOrganizations(organizations: Organization[]) {
      this.userOrganizations = organizations
    },
    
    setUnreadCount(count: number) {
      this.unreadCount = count
    },
    
    setShowUnreadCount(show: boolean) {
      this.showUnreadCount = show
    },
    
    setCurrentUser(user: User) {
      this.user = user
    },
    
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token) // 保存token到localStorage
    },
    
    resetToken() {
      this.token = null
      this.user = null
      this.currentOrganization = null
      this.userOrganizations = []
      localStorage.removeItem('token') // 从localStorage移除token
      localStorage.removeItem('currentOrganization') // 从localStorage移除当前组织
    },
    
    setPageTitle(title: string) {
      this.pageTitle = title
      // 同时更新文档标题
      document.title = title ? `${title} - 小采灵犀智能对账系统` : '小采灵犀智能对账系统'
    },
    
    async getUserInfo() {
      // 如果已经有用户信息，直接返回
      if (this.user) {
        return this.user
      }
      
      // 检查是否有token
      if (!this.token) {
        throw new Error('没有token')
      }
      
      try {
        const response = await authAPI.getCurrentUser();
        if (response.success && response.data) {
          this.user = {
            id: response.data.id,
            name: response.data.name || '',
            avatar: '',
            isAdmin: (response.data.isAdmin || response.data.role === 'admin') || false,
            role: response.data.role
          };
          return response.data;
        } else {
          // 即使后端返回失败，也返回null而不是抛出错误
          console.warn('获取用户信息失败:', response.message || '获取用户信息失败');
          return null;
        }
      } catch (error: any) {
        console.error('获取用户信息失败:', error);
        // 即使获取用户信息失败，也返回null而不是抛出错误
        return null;
      }
    },
    
    async loadUserOrganizations() {
      try {
        const response: any = await organizationAPI.getUserOrganizations('current')
        if (response.success) {
          this.userOrganizations = response.data
          
          // 如果当前没有设置组织，且用户有组织，则设置第一个组织为当前组织
          if (!this.currentOrganization && this.userOrganizations.length > 0) {
            const storedOrg = localStorage.getItem('currentOrganization')
            if (storedOrg) {
              const org = JSON.parse(storedOrg)
              if (this.userOrganizations.some((o: any) => o.id === org.id)) {
                this.currentOrganization = org
              } else {
                this.currentOrganization = this.userOrganizations[0]
                localStorage.setItem('currentOrganization', JSON.stringify(this.currentOrganization))
              }
            } else {
              this.currentOrganization = this.userOrganizations[0]
              localStorage.setItem('currentOrganization', JSON.stringify(this.currentOrganization))
            }
          }
          
          return response.data
        } else {
          console.error('加载用户组织失败:', response.message)
          return []
        }
      } catch (error) {
        console.error('加载用户组织失败:', error)
        return []
      }
    },
    
    async switchOrganization(organization: Organization) {
      this.currentOrganization = organization
      localStorage.setItem('currentOrganization', JSON.stringify(organization))
      
      // 重新加载用户信息以确保权限正确
      await this.getUserInfo()
    }
  }
})